<!--
 * @FilePath: Role.vue
 * @Author: jack
 * @Date: 2025-02-14 14:29:10
 * @LastEditors: liyin 2179253556@qq.com
 * @LastEditTime: 2025-07-31 09:32:35
 * Copyright: 2025 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion: 
-->
<template>
    <div class="user-info-box">
        <Table :marginTop="false" :data="tableData" :config="tableConfig" @handleEdit="handleEdit" :showPage="false">
        </Table>
        <!-- 权限列表菜单抽屉 -->
        <el-drawer v-model="drawer" title="分配权限" :direction="direction" style="width: 40%;">
            <div class="drawer-box">
                <el-checkbox style="margin-left:14px;" v-model="selectAll" :label="selectAll ? '取消全选' : '全选'"
                    @change="selectAllChange" />
                <el-tree ref="treeRef" :data="treeData" default-expand-all show-checkbox node-key="uuid"
                    :render-content="renderContent" :props="defaultProps" :default-checked-keys="selectUUids"
                    @check-change="currentChanged" @check="getCurrentNode" :check-strictly="true"></el-tree>
            </div>
            <div class="drawer-btn">
                <el-button type="primary" @click="submitDrawer" :loading="loading">{{
                    loading ?
                        '正在提交,请稍等...' : '确 定'
                }}</el-button>
                 <el-button @click="closeDrawer">取 消</el-button>
            </div>
        </el-drawer>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElTree } from 'element-plus'
import { PiniaStore } from '../../store'
// 引入专属的request配置
import { RoleList, getRolePermissionList, setPermission, getLoginLeftMenuList } from '../../components/Api/Operation'
const store = PiniaStore()
const dialogVisible = ref(false)
const addRole = reactive({
    uuid: '',
    role_name: '',
    status: '1',
})
const rules = reactive<FormRules>({
    role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
})
const loading = ref<boolean>(false)
const drawer = ref(false)
const direction = ref('rtl')
const treeData = ref<any>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultProps = {
    children: 'children',
    label: 'menu_name',
}
const selectAll = ref(false)
// 表格数据
const tableData = ref([])
const tableConfig = ref([
    { name: 'index', label: '序号', width: '60', type: 'index', checked: true, },
    { name: 'role_name', label: '角色名称', width: '', checked: true, disabled: true, },
    {
        name: 'status',
        label: '状态',
        width: '',
        checked: true,
        type: 'status',
        disabled: true,
        //状态 1-有效 0-无效
        formatter: [
            { name: 0, label: '无效', status: 'danger' },
            { name: 1, label: '有效', status: 'success' }
        ]
    },
    { name: 'create_time', label: '设置时间', width: '', checked: true },
    { name: 'remark', label: '备注', type: 'change', width: '', checked: true },
    {
        name: '',
        label: '操作',
        width: '',
        type: 'edit',
        checked: true,
        formatter: [
            // { name: 'Edit', label: '编辑', font: true, link: true },
            { name: 'Setting', label: '分配权限', font: true, link: true }
        ]
    }
])
// 获取菜单列表
const selectUUids = ref<any>([])
const getApiList = async (uuid: any) => {
    const res: any = await getRolePermissionList({ role_uuid: uuid })
    if (res.code !== 1) return ElMessage.error(res.message)
    treeData.value = await changeName(res.data)
    selectUUids.value = []
    findSelectedItems(JSON.parse(JSON.stringify(res.data)))
    // treeRef.value!.setCheckedKeys(selectUUids.value)
    setTimeout(() => {
        changeCss()
    }, 10);
}
const changeName = async (items: any) => {
    items.forEach((item: any) => {
        if (Number(item.type) == 1) {
            // 菜单类型
            item.menu_name = `${item.menu_name}`
        } else {
            // 按钮类型
            item.menu_name = `${item.menu_name}`
        }
        if (item.children && item.children.length > 0) {
            changeName(item.children)
        }
    });
    return items
}
// 递归查找所选中的id
const findSelectedItems = async (items: any) => {
    items.forEach((item: any) => {
        if (Number(item.is_check) === 1) { // 假设每个元素都有一个selected属性表示是否选中
            selectUUids.value.push(item.uuid)
        }
        if (Number(item.type) == 1) {
            // 菜单类型
            item.menu_name = `${item.menu_name}`
        } else {
            // 按钮类型
            item.menu_name = `${item.menu_name}`
        }
        if (item.children && item.children.length > 0) {
            findSelectedItems(item.children)
        }
    });
    return selectUUids.value
}
// 获取角色列表
const getRoleList = async () => {
    const res: any = await RoleList()
    // res.data.forEach((item: any, index: number) => {
    //     if (item.uuid === '26258978-74f0-5604-6c35-78781b5f254d') {
    //         res.data.splice(index, 1)
    //     }
    // });
    tableData.value = res.data
}
// 点击设置菜单权限
const closeDrawer = async () => {
    drawer.value = false
    refresh()
}
const submitDrawer = async () => {
    loading.value = true
    let arr = []
    // if (treeRef.value != undefined) {
    //     arr = treeRef.value!.getCheckedKeys(false)
    // } else {
    //     arr = selectUUids.value
    // }
    let zi = treeRef.value!.getCheckedKeys()//返回选中子节点的key
    let fu = treeRef.value!.getHalfCheckedKeys()//返回选中子节点的父节点的key
    arr = zi.concat(fu)
    if (arr.length === 0) {
        return ElMessage.error('请选择角色拥有的权限菜单!')
    }
    const params = {
        role_uuid: addRole.uuid ? addRole.uuid : '',
        menu_uuids: arr.length > 0 ? arr.join(',') : ''
    }
    const res: any = await setPermission(params)
    if (res.code !== 1) {
        loading.value = false
        return ElMessage.error(res.message)
    }
    ElMessage.success(res.message)
    loading.value = false
    drawer.value = false
}
const selectAllChange = () => {
    if (selectAll.value) {
        treeRef.value!.setCheckedNodes(treeData.value); // 全选当前显示的节点（包括子节点）
        // 或者使用递归方法手动设置所有节点为选中状态：
        setAllChecked(treeData.value, true);
    } else {
        treeRef.value!.setCheckedNodes([])
    }
}
const currentChanged = () => {
    if (treeRef.value!.getCheckedKeys().length < getTreeNodeIDList(treeData.value)) {
        selectAll.value = false
    } else {
        // 全部选中
        selectAll.value = true
    }
}
const setAllChecked = (nodes: any, checked: any) => {
    nodes.forEach((node: any) => {
        if (node.children) {
            setAllChecked(node.children, checked); // 递归处理子节点
        }
        treeRef.value!.setChecked(node, checked, true); // 设置当前节点选中状态，第三个参数 true 表示不触发回调函数中的 check-change 事件。
    });
}
//获取树列表的所有节点  ==>  这里是计算出所有子节点的个数
const getTreeNodeIDList = (data: any) => {
    var str = 0;
    const getStr = (list: any) => {
        list.forEach((row: any) => {
            if (row.children) {
                getStr(row.children);
                str += 1
            } else {
                str += 1
            }
        });
    };
    getStr(data)
    return str;
}
const refresh = async () => {
    if (treeRef.value != undefined) {
        treeRef.value!.setCheckedKeys(selectUUids.value, false)
    }
}
const handleEdit = async (item: any, val: any) => {
    if (val === 'Edit') {
        // 编辑
        dialogVisible.value = true
        nextTick(() => {
            addRole.role_name = item.role_name
            addRole.uuid = item.uuid
            addRole.status = item.status
            refresh()
        })
    } else if (val === 'Setting') {
        // 分配权限
        addRole.uuid = item.uuid
        drawer.value = true
        await getApiList(item.uuid)
    }
}
const renderContent = (h: any, { node, data, store }: any) => {//树节点的内容区的渲染 Function
    let classname = "";
    // 由于项目中有三级菜单也有四级级菜单，就要在此做出判断
    if (node.level === 3) {
        classname = "foo";
    }
    return h(
        "p",
        {
            class: classname
        },
        node.label
    )
}
const changeCss = () => {
    var levelName: any = document.getElementsByClassName("foo"); // levelname是上面的最底层节点的名字
    for (var i = 0; i < levelName.length; i++) {
        levelName[i].parentNode.style.cssFloat = "left"; // 最底层的节点，包括多选框和名字都让他左浮动
        levelName[i].parentNode.style.styleFloat = "left";
        levelName[i].parentNode.onmouseover = function () {
            this.style.backgroundColor = "#fff";
        };
    }
}
const getCurrentNode = (data: any) => {
    let node = treeRef.value!.getNode(data);
    childNodes(node)
    parentNodes(node)
    selectUUids.value = treeRef.value!.getCheckedKeys();
}
//具体方法可以看element官网api
const childNodes = (node: any) => {
    let len = node.childNodes.length;
    for (let i = 0; i < len; i++) {
        node.childNodes[i].checked = node.checked;
        childNodes(node.childNodes[i]);
    }
}
const parentNodes = (node: any) => {
    if (node.parent) {
        for (let key in node) {
            if (key == "parent") {
                node[key].checked = true;
                parentNodes(node[key]);
            }
        }
    }
}
onMounted(() => {
    store.setSearchHeight(0)
    store.setTableHeight2()
    getRoleList()
})
</script>
<style lang="scss" scoped>
.user-info-box {
    width: 100%;
}

:deep(.el-tree-node__content) {
    height: 32px;
}

:deep(.el-checkbox:last-of-type) {
    margin-right: 8px;
}

:deep(.el-tree-node__content) {
    display: flex;
    align-items: center;
}

:deep(.el-tree-node__children) {
    overflow: hidden;
    background-color: transparent;
}

:deep(.el-drawer) {
    width: 420px !important;
}
</style>
